package com.bw.demoseckill.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.demoseckill.entity.TbGoods;
import com.bw.demoseckill.mapper.GoodsMapper;
import com.bw.demoseckill.utils.ConstUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@EnableScheduling
@Component
@Slf4j
public class CouponTask {

    // 1.固定间隔 2.定点

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Scheduled(cron = "* 24 15 * * * ")
    public void beginCouponTask(){

        //--1 检查商品信息
        TbGoods goods = goodsMapper.selectOne(
                new QueryWrapper<TbGoods>()
                        .eq("status", 0)
                        .orderByDesc("start_time")
                        .last("limit 1"));

        if (goods==null){
            log.info("没有特惠活动");
            return;
        }
        //--2 生成商品，放入redis中

        //循环加入商品
        for (int idx=0;idx<goods.getNum();idx++){
            redisTemplate.opsForList().leftPush(ConstUtils.WAITTING_COUPON_KEY,goods.getId());
        }

        //设置优惠卷的过期时间

        //增加了一个set，存储的是已经抢到商品的用户的id
        redisTemplate.opsForSet().add(ConstUtils.CATCH_COUPON_KEY,0);

        redisTemplate.expire(ConstUtils.WAITTING_COUPON_KEY,1, TimeUnit.HOURS);

        //设置已抢到商品用户集合的时间
        redisTemplate.expire(ConstUtils.CATCH_COUPON_KEY,1, TimeUnit.HOURS);

        //--3 修改优惠活动的状态
        goods.setStatus(1);
        goodsMapper.updateById(goods);


        System.out.println("开始抢购了");
    }


}
